package com.yequan.designpattern.singleton.lazysingleton;

/**
 * @Auther: yq
 * @Date: 2019/1/9 13:43
 * @Description:
 */
public class LowThreadSafeLazySingleton {

    /**
     * 懒汉式（线程安全，效率低下）
     * 使用synchronized同步锁解决多线程下产生多个instance对象的问题
     * 效率低：多线程情况下，当一个线程想要获取该对象，必须等上一个线程释放锁才能进行
     */
    private static LowThreadSafeLazySingleton instance = null;

    private LowThreadSafeLazySingleton() {
    }

    public static LowThreadSafeLazySingleton getInstance() {
        synchronized (LowThreadSafeLazySingleton.class) {
            if (null == instance) {
                try {
                    Thread.sleep(300);//模仿耗时操作
                    instance = new LowThreadSafeLazySingleton();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return instance;
    }

    /**
     * 测试懒汉式在代码块加锁的情况下，线程安全
     *
     * @param args
     */
    public static void main(String[] args) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread1 >>>>> " + LowThreadSafeLazySingleton.getInstance().hashCode());
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread2 >>>>> " + LowThreadSafeLazySingleton.getInstance().hashCode());
            }
        });
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("thread3 >>>>> " + LowThreadSafeLazySingleton.getInstance().hashCode());
            }
        });

        thread1.start();
        thread2.start();
        thread3.start();
    }

}
